package com.house.controller;


import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.house.common.Result;
import com.house.entity.Order;
import com.house.service.HouseService;
import com.house.service.LeaseService;
import com.house.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;


/**
 * 订单管理
 */
@Controller
@RequestMapping("order")
public class OrderController {


    @Autowired
    private OrderService orderService;

    @Autowired
    private HouseService houseService;

    @Autowired
    private LeaseService leaseService;



    /**
     * 订单信息管理页
     * @return
     */
    @GetMapping("manage")
    public String manage() {
        return "admin/orderManage";
    }

    @PostMapping("manage/list")
    @ResponseBody
    public List<Order> list(Order order) {
        return orderService.list(Wrappers.<Order>query().orderByDesc("create_time"));
    }


    /**
     * 合同页
     * @return
     */
    @GetMapping("contract")
    public String contract(Model model, String orderId) {
        Order order = orderService.getById(orderId);
        order.setHouse(houseService.getById(order.getHouseId()));
        order.setLease(leaseService.getById(order.getLeaseId()));


        long day = DateUtil.between(DateUtil.parseDate(order.getCheckInTime()), DateUtil.parseDate(order.getCheckOutTime()), DateUnit.DAY);
        order.setDay(day);
        model.addAttribute("order", order);
        return "pc/contract";
    }



    /**
     * 支付
     * @return
     */
    @GetMapping("pay")
    public String pay(Model model, String orderId) {
        Order order = orderService.getById(orderId);
        model.addAttribute("order", order);
        return "pc/pay";
    }


    /**
     * 保存/更新订单信息
     * @param order
     * @return
     */
    @PostMapping("saveOrUpdate")
    @ResponseBody
    public Result saveOrUpdate(Order order){

        // 新增订单默认改为待支付
        if(StrUtil.isEmpty(order.getStatus())) {
            order.setStatus("0");
        }
        orderService.saveOrUpdate(order);
        return Result.ok(order);
    }


    /**
     * 支付， 修改订单状态
     * @param order
     * @return
     */
    @PostMapping("updateStatus")
    @ResponseBody
    public Result updateStatus(Order order){

        // 举个例子
        orderService.lambdaUpdate().set(Order::getStatus, "1").eq(Order::getId, order.getId()).update(new Order());

        return Result.ok();
    }
}
